/**
 * 
 */
package com.monkeyboy.security.social.qq.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.social.SocialAutoConfigurerAdapter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.social.connect.ConnectionFactory;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionSignUp;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.jdbc.JdbcUsersConnectionRepository;
import org.springframework.web.servlet.View;

import com.monkeyboy.security.properties.SecurityProperties;
import com.monkeyboy.security.social.qq.ConnectSuccessView;
import com.monkeyboy.security.social.qq.connect.QQConnectFactory;
import com.monkeyboy.security.social.qq.properties.QQProperties;

/**
 * @Description QQAutoConfig 针对qq返回结果的一些操作
 * @author Gavin<br>
 *         2019年8月27日
 */
@Configuration
@ConditionalOnProperty(prefix = "com.monkeyboy.social.qq", name = "app-id") // 如果没有这个属性配置，那么这个配置类就不会起作用
public class QQAutoConfig extends SocialAutoConfigurerAdapter {
	@Autowired
	private SecurityProperties securityProperties;

	@Autowired
	private DataSource dataSource;
	@Autowired(required = false)
	private ConnectionSignUp qqConnecttionSignUp;

	/*
	 */
	@Override
	protected ConnectionFactory<?> createConnectionFactory() {
		QQProperties qqConfig = securityProperties.getSocial().getQq();
		return new QQConnectFactory(qqConfig.getProviderId(), qqConfig.getAppId(), qqConfig.getAppSecret());
	}

	@Override
	public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
		JdbcUsersConnectionRepository repository = new JdbcUsersConnectionRepository(dataSource,
				connectionFactoryLocator, Encryptors.noOpText());
		// repository.setTablePrefix("prefix_");

		if (qqConnecttionSignUp != null) {
			repository.setConnectionSignUp(qqConnecttionSignUp);
		}

		return repository;
	}

	// 设置QQ绑定成功和解绑成功的返回视图
	@Bean({ "connect/qqConnect", "connect/qqConnected" })
	@ConditionalOnMissingBean(name = "qqConnectedView") // 如果不想用这个bean的话就向spring容器中注入一个名为qqConnectedView名字的bean来进行覆盖
	public View callbackConnectedView() {
		return new ConnectSuccessView();
	}
}
